/*----------------------------------------------------------\\
|| Mancala                                                  ||
|| CS-340 with Professor Troy                               ||
|| Joshua Jung and Eugene Magdel                            ||
|| April 29, 2011                                           ||
\\----------------------------------------------------------*/
#include "mancala_ai.h"

MancalaAi::MancalaAi(int _player_num){
  player_num = _player_num;
}

int MancalaAi::next_move(){
  int starting_position = player_num * 7 + 1; //0 * 7 + 1 = 1 
  //If board has any captures try to get them
  Cup * current_cup = &Cup::cup_at(starting_position);
  cout << "capture step, starting poisition is " << endl;
  bool found_empty_cup = false;
  while(!current_cup -> is_mancala()){
    if(current_cup -> empty() && !current_cup -> get_across().empty()){
      break;
    }
    current_cup = current_cup -> get_next();
    cout << "capture step, cehcking cup: " << current_cup -> get_index() << endl;
  }
  if(!current_cup -> is_mancala() && current_cup -> empty() && !current_cup -> get_across().empty()){
    int target_cup_index = current_cup -> get_index();
    Cup * current_cup = &Cup::cup_at(starting_position);
    while(current_cup -> get_index() < target_cup_index){
      if(current_cup -> gem_count() == current_cup -> get_index() - target_cup_index - 1){
        return current_cup -> get_index();
      }
      current_cup = current_cup -> get_next();
    }
  }
  //If you can get last gem to land in your mancala, get position of the cup
  current_cup = &Cup::cup_at(starting_position);
  int i = 6;
  while(!current_cup -> is_mancala()){
    cout << "gem count is " << i << endl;
    cout << "mancala index: " << current_cup -> get_index() << endl;
    cout << "number of gems: " << current_cup -> gem_count() << endl;
    if(current_cup -> gem_count() == i){
      return current_cup -> get_index();
    }
    current_cup = current_cup -> get_next();
    i--;
  }
  //Randomly select cup
  int r = (rand() % 6) + starting_position;
  int tries = 0;

  while (Cup::cup_at(r).gem_count() == 0 && tries < 50)
  {
      r = (rand() % 6) + starting_position;
      tries ++;
  }

  return r;
}

int MancalaAi::player_number(){
  return player_num;
}
